package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.SpecGroupDTO;
import com.leyou.common.dto.SpecParamDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {


    @Autowired
    private SpecGroupService specGroupService;

    @Autowired
    private SpecParamService specParamService;


    @Override
    @Transactional
    public List<SpecGroupDTO> querySpecListById(long id) {

        /*
        *
        *  SELECT * FROM tb_spec_group g LEFT JOIN  tb_spec_param p
        *  ON g.id =p.group_id  WHERE  g.category_id =#{id}
        * */
        //1.根据分类id查询规格组参数
        List<SpecGroupDTO> groupList = SpecGroupDTO.convertEntityList(specGroupService.query()
                .eq("category_id", id).list());
        //2.判断是否为空
        if(CollectionUtils.isEmpty(groupList)){
            //若为空,抛出异常
            throw new LyException(404, "该分类下的规格组不存在！");
        }
        //3.查询每个组的规格参数
        for (SpecGroupDTO specGroupDTO : groupList) {
            Long groupId = specGroupDTO.getId();
            List<SpecParamDTO> params = specParamService.queryParamList(null, groupId, null);
            specGroupDTO.setParams(params);
        }


        return groupList;
    }
}
